package edu.hawaii.duedates;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;

/**
 * Due Date Red demonstrates simple use of httpunit to retrieve and parse a web page. Original
 * author by Philip Johnson.
 * 
 * @author Ka Hung Phillip Lau
 * @author Creighton Okada
 */
public final class DueDates {
  /**
   * Private constructor to silence PMD warning 'All methods are static'.
   */
  private DueDates() {
    //No code needed.
  }
  /**
   * The main class illustrates the use of this code to login in systems.
   * 
   * @param params Up to six strings: 
   *           Libraries: -uhm (University of Hawaii Manoa Library) 
   *                      -hsl (Hawaii State Library)
   *  Library Parameters: UH Manoa Library parameters: uhID, uhLastName 
   *                      Hawaii State Library parameters: hiStateId, hiStatePassword
   * @throws Exception If problems occur accessing the library sites.
   */
  public static void main(String[] params) throws Exception {
    try {
      if (params[0].equals("-uhm") && params[1].equals("-hsl")) {
        checkUhManoaLibrary(params[2], params[3]);
        checkHawaiiStateLibrary(params[4], params[5]);
      }
      else if (params[0].equals("-hsl") && params[1].equals("-uhm")) {
        checkHawaiiStateLibrary(params[2], params[3]);
        checkUhManoaLibrary(params[4], params[5]);
      }
      else if (params[0].equals("-uhm")) {
        checkUhManoaLibrary(params[1], params[2]);
      }
      else if (params[0].equals("-hsl")) {
        checkHawaiiStateLibrary(params[1], params[2]);
      }
      else if (params[0].equals("-sort")) {
        if (params[1].equals("library")) {
          System.out.println("a");
          //sort books in alphabetical library order (Hawaii state, then UH Manoa)
        }
        else if (params[1].equals("duedate")) {
          System.out.println("b");
          //sort books in chronological due date
        }
        else if (params[1] == null) {
          System.out.println("c");
          //default to library sort
        }
        else {
          System.out.println("d");
          //error
        }
      }
      else if (params[0].equals("-within")) {
        try {
          int numberOfDays = Integer.parseInt(params[1]);
          
          if (Integer.valueOf(params[1]) <= (Integer.valueOf(0))) {
            obtainAllBooks();
          }
          else {
            obtainBooksWithin(numberOfDays);
          }
        }
        catch (NumberFormatException e) {
          System.out.println("An integer was not entered.  Enter an integer.");
        }
        catch (ArrayIndexOutOfBoundsException e) {
          obtainAllBooks();
        }
      }
      else {
        // incorrect param argument(s)
        System.out.println("Incorrect library name.  Only libraries for the University" +
            "of Hawaii at Manoa (-uhm) and Hawaii State Library (-hsl) may be entered." +
            "\nEnter either or both and provide sufficient credentials.");
      }
    }
    catch (Exception IndexOutOfBounds) {
      System.out.println("Invalid parameters entered.  \nCheck if first parameter is a valid" +
          " library and that login parameters are valid.  If two libraries were entered, " +
          "check to make sure they are accepted libraries (-uhm, -hsl) and the credentials" +
          "provided are accepted locally and are entered in the correct order" +
          "\nExample (for one library): -uhm <UH ID number> <UH ID owner's Last Name>" +
          "\nExample (for more than one library): -uhm -hsl <UH ID number> <UH ID owner's " +
          "Last Name> <HI State Library Barcode> <HI State Library Pin Number>");
    }
  }
  /**
   * Obtains information from HI State Library.
   * @param hiStateId Barcode number
   * @param hiStatePassword Pin number
   * @throws Exception if login is incorrect
   */
  private static void checkHawaiiStateLibrary(String hiStateId, 
      String hiStatePassword) throws Exception {
    System.out.printf("Getting data from Hawaii State Library System " +
        "(this can take 1 minute)%n");
    HawaiiStateLibrary hiInfo = new HawaiiStateLibrary();
    System.out.printf("\nResults for Hawaii State Library:\n");
    List<Book> books = hiInfo.getHawaiiStateInfo(hiStateId, hiStatePassword);
    
    if (books.isEmpty()) {
      System.out.printf("\nNo books checked out.");
    }
    else {
      StringBuilder outputString = new StringBuilder();
      Formatter formatter = new Formatter(outputString);
      DateFormat newFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);

      String format = "|%-70.70s\t|%-10s|\n";
      formatter.format(format, "| Title", "Due Date"); 
      
      for (int i = 0; i < books.size(); i++) {
        formatter.format(format, books.get(i).getBookTitle(), 
            newFormat.format(books.get(i).getBookDueDate()));
      }
      System.out.println(outputString);
    }
  }
  /**
   * Obtains information from UH Manoa Library.
   * @param id ID number
   * @param lastName Last name of respective ID number
   * @throws Exception if login is incorrect
   */
  private static void checkUhManoaLibrary(String id, String lastName) throws Exception {
    System.out.printf("Getting data from UH Manoa%n");
    UhManoaLibrary uhInfo = new UhManoaLibrary();
    System.out.printf("Results for UH Manoa:%n %s%n", uhInfo.getUhInfo(id, lastName));
  }
  /**
   * Method that prints a list of books from within a certain number of days that they're due.
   * @param numberOfDaysWithin the number of days specified.  Prints all books due before that
   *                           date
   * @throws Exception if login is incorrect
   */
  private static void obtainBooksWithin(int numberOfDaysWithin) throws Exception {
    //creates a new format
    DateFormat newFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
  
    //Create a new calendar date with todays date by default
    Calendar daysLater = Calendar.getInstance();
    //change to "within" days later
    daysLater.add(Calendar.DAY_OF_MONTH, numberOfDaysWithin);
  
    HawaiiStateLibrary hiInfo = new HawaiiStateLibrary();
    List<Book> books = hiInfo.getHawaiiStateInfo("barcode", "pin");
    //ADD UH INFO HERE
  
    if (books.isEmpty()) {
      System.out.println("There are no books borrowed.");
    }
    else {
      System.out.println("Books due in " + numberOfDaysWithin + " days: ");
      StringBuilder outputString = new StringBuilder();
      Formatter formatter = new Formatter(outputString);

      String format = "|%-70.70s\t|%-10s|\n";
      formatter.format(format, "| Title", "Due Date"); 
      for (int i = 0; i < books.size(); i++) {
        Calendar fromDate = Calendar.getInstance();
        fromDate.setTime(books.get(i).getBookDueDate());
        if (fromDate.compareTo(daysLater) < 0) {
          formatter.format(format, books.get(i).getBookTitle(), 
              newFormat.format(books.get(i).getBookDueDate()));
        }
      }
      System.out.println(outputString);
    }
  }
  /**
   * Method that prints out all books due given an invalid integer or zero.
   * @throws Exception if login is incorrect
   */
  private static void obtainAllBooks() throws Exception {
    DateFormat newFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
    
    HawaiiStateLibrary hiInfo = new HawaiiStateLibrary();
    List<Book> books = hiInfo.getHawaiiStateInfo("barcode", "pin");
    //ADD UH INFO HERE
    
    if (books.isEmpty()) {
      System.out.println("There are no books borrowed.");
    }
    else {
      System.out.println("Returning a list of all books: ");
      StringBuilder outputString = new StringBuilder();
      Formatter formatter = new Formatter(outputString);

      String format = "|%-70.70s\t|%-10s|\n";
      formatter.format(format, "| Title", "Due Date"); 
      for (int i = 0; i < books.size(); i++) {
        formatter.format(format, books.get(i).getBookTitle(), 
            newFormat.format(books.get(i).getBookDueDate()));
      }
      System.out.println(outputString);
    }
  }
}
